<template>
  <div class="app-container">
    <el-card v-show="showSearch" class="mb10" shadow="hover">
      <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="120px" size="small">
        <el-form-item label="优惠券名称" prop="params.couponName">
          <el-input
            v-model="queryParams.params.couponName"
            clearable
            placeholder="请输入优惠券名称"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="优惠券类型" prop="params.couponType">
          <el-select v-model="queryParams.params.couponType" placeholder="请输入优惠券类型">
            <el-option
              v-for="dict in dict.type.coupon_type"
              :key="dict.dictCode"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="可用油站" prop="params.stationsLimit">
          <el-select v-model="queryParams.params.stationsLimit" placeholder="可用油站">
            <el-option
              v-for="item in stationList"
              :key="item.id"
              :label="item.fullName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="可用油品" prop="params.fuelsLimit">
          <el-select v-model="queryParams.params.fuelsLimit" placeholder="可用油品">
            <el-option
              v-for="item in fuelList"
              :key="item.id"
              :label="item.fuelName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="可用星期" prop="params.daysLimit">
          <el-select v-model="queryParams.params.daysLimit" placeholder="可用星期">
            <el-option
              v-for="dict in dict.type.sys_week"
              :key="dict.dictCode"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="ml10">
          <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="hover">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['market:couponTemplate:add']"
            icon="el-icon-plus"
            plain
            size="mini"
            type="primary"
            @click="handleAdd"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['market:couponTemplate:edit']"
            :disabled="single"
            icon="el-icon-edit"
            plain
            size="mini"
            type="success"
            @click="handleUpdate"
          >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['market:couponTemplate:remove']"
            :disabled="multiple"
            icon="el-icon-delete"
            plain
            size="mini"
            type="danger"
            @click="handleDelete"
          >删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['market:couponTemplate:export']"
            icon="el-icon-download"
            plain
            size="mini"
            type="warning"
            @click="handleExport"
          >导出
          </el-button>
        </el-col>
        <right-toolbar :columns="columns" :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="couponTemplateList" border @selection-change="handleSelectionChange"
                @sort-change="handleSortChange">
        <el-table-column align="center" type="selection" width="55"/>
        <el-table-column v-if="columns[0].visible" align="center" label="ID" prop="id" show-overflow-tooltip/>
        <el-table-column v-if="columns[1].visible" align="center" label="优惠券名称" prop="couponName"
                         show-overflow-tooltip/>
        <el-table-column v-if="columns[2].visible" align="center" label="优惠券类型" prop="couponType"
                         show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="dict.type.coupon_type" :value="scope.row.couponType"/>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[3].visible" align="center" label="消费金额" prop="consumptionAmount"
                         show-overflow-tooltip/>
        <el-table-column v-if="columns[4].visible" align="center" label="优惠金额" prop="discountAmount"
                         show-overflow-tooltip>
          <template #default="scope">
            {{
              scope.row.couponType === '2' ? scope.row.discountRatio + '%' : scope.row.discountAmount +
                (scope.row.couponType === '3' ? '元/升' : '元')
            }}
          </template>
        </el-table-column>
        <el-table-column v-if="columns[5].visible" align="center" label="开始时间" prop="startTime"
                         show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.startTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[6].visible" align="center" label="结束时间" prop="endTime" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.endTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[7].visible" align="center" label="可用油站" prop="stationsLimitName"
                         show-overflow-tooltip/>
        <el-table-column v-if="columns[8].visible" align="center" label="可用油品" prop="fuelsLimitName"
                         show-overflow-tooltip/>
        <el-table-column v-if="columns[9].visible" align="center" label="可用星期" prop="daysLimit"
                         show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="dict.type.sys_week" :value="scope.row.daysLimit.split(',')"/>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[10].visible" align="center" label="是否可以转赠" prop="transferable"
                         show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.transferable"/>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[11].visible" align="center" label="是否可以叠加" prop="stackable"
                         show-overflow-tooltip/>
        <el-table-column v-if="columns[12].visible" align="center" label="延迟天数" prop="delayDays"
                         show-overflow-tooltip/>
        <el-table-column v-if="columns[13].visible" align="center" label="使用目的" prop="purpose"
                         show-overflow-tooltip/>
        <el-table-column v-if="columns[14].visible" align="center" label="使用说明" prop="instructions"
                         show-overflow-tooltip/>
        <el-table-column v-if="columns[15].visible" align="center" label="排序编码" prop="orderNumber"
                         show-overflow-tooltip/>
        <el-table-column v-if="columns[16].visible" align="center" label="创建时间" prop="createDate"
                         show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.createDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[17].visible" align="center" label="备注信息" prop="remark"
                         show-overflow-tooltip/>
        <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button
                v-hasPermi="['market:couponTemplate:edit']"
                icon="el-icon-edit-outline"
                size="mini"
                type="text"
                @click="handleUpdate(scope.row)"/>
            </el-tooltip>

            <el-tooltip content="删除" placement="top">
              <el-button
                v-hasPermi="['market:couponTemplate:remove']"
                icon="el-icon-delete"
                size="mini"
                type="text"
                @click="handleDelete(scope.row)"/>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :limit.sync="queryParams.pageSize"
        :page.sync="queryParams.pageNum"
        :total="total"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改优惠券模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="1100px">
      <el-form ref="form" :model="form" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="优惠券名称" prop="couponName">
              <el-input v-model="form.couponName" placeholder="请输入优惠券名称"/>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="优惠券类型" prop="couponType">
              <el-select v-model="form.couponType" placeholder="请选择优惠券类型">
                <el-option
                  v-for="dict in dict.type.coupon_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item v-if="!isWash" label="消费金额" prop="consumptionAmount">
              <el-input v-model="form.consumptionAmount" placeholder="请输入消费金额"/>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item v-if="!isDiscount && !isWash" label="优惠金额" prop="discountAmount">
              <el-input v-model="form.discountAmount" placeholder="请输入优惠金额"/>
            </el-form-item>
          </el-col>

          <el-col v-if="isDiscount && !isWash" :span="6">
            <el-form-item label="折扣比例(%)" prop="discountRatio">
              <el-input v-model="form.discountRatio" placeholder="请输入折扣比例"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="是否可以转赠" prop="transferable">
              <el-select v-model="form.transferable" clearable placeholder="是否可以转赠">
                <el-option
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="是否可以叠加" prop="stackable">
              <el-select v-model="form.stackable" clearable placeholder="是否可以叠加">
                <el-option
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="延迟天数" prop="delayDays">
              <el-input v-model="form.delayDays" placeholder="请输入延迟天数"/>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="排序编码" prop="orderNumber">
              <el-input v-model="form.orderNumber" placeholder="请输入排序编码"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="时间范围：" prop="startTime">
              <el-date-picker
                v-model="dateRange"
                end-placeholder="结束日期"
                range-separator="至"
                start-placeholder="开始日期"
                style="width: 100%"
                type="datetimerange"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="可用油站：" prop="stationsLimit">
              <el-checkbox-group v-model="checkStationList">
                <el-checkbox v-for="item in stationList" :key="item.id" :label="item.id+''">
                  {{ item.fullName }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="可用油品：" prop="fuelsLimit">
              <el-checkbox-group v-model="checkFuelList">
                <el-checkbox v-for="item in fuelList" :key="item.id" :label="item.id+''">
                  {{ item.fuelName }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="可用星期：" prop="daysLimit">
              <el-checkbox-group v-model="checkWeekList">
                <el-checkbox v-for="dict in dict.type.sys_week" :key="dict.dictCode" :label="dict.value">
                  {{ dict.label }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="使用目的" prop="purpose">
              <el-input v-model="form.purpose" placeholder="请输入使用目的"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="使用说明" prop="instructions">
              <el-input v-model="form.instructions" :autosize="{ minRows: 2, maxRows: 20}" placeholder="请输入内容"
                        type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注信息" prop="remark">
              <el-input v-model="form.remark" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入备注信息"
                        type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addCouponTemplate,
  getCouponTemplate,
  listCouponTemplate,
  updateCouponTemplate
} from "@/api/market/couponTemplate";
import {formatDateTime, nowCnFormatDateTime} from "@/utils/date";
import {selectList as selectStationList} from "@/api/base/station";
import {selectList as selectFuelList} from "@/api/base/fuel";

export default {
  name: "CouponTemplate",
  dicts: ['coupon_type', 'sys_week', 'sys_yes_no'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 日期范围
      dateRange: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 优惠券模板表格数据
      couponTemplateList: [],
      weekList: [],
      stationList: [],
      fuelList: [],
      // 已选星期
      checkWeekList: [],
      checkStationList: [],
      checkFuelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sortName: 'id',
        sortOrder: 'desc',
        params: {
          mchId: undefined,
          couponName: undefined,
          couponType: undefined,
          consumptionAmount: undefined,
          discountAmount: undefined,
          discountRatio: undefined,
          startTime: undefined,
          endTime: undefined,
          stationsLimit: undefined,
          fuelsLimit: undefined,
          daysLimit: undefined,
          transferable: undefined,
          stackable: undefined
        }
      },
      // 列信息
      columns: [
        {key: 0, label: `ID`, visible: true},
        {key: 1, label: `优惠券名称`, visible: true},
        {key: 2, label: `优惠券类型`, visible: true},
        {key: 3, label: `消费金额`, visible: true},
        {key: 4, label: `优惠金额`, visible: true},
        {key: 5, label: `开始时间`, visible: true},
        {key: 6, label: `结束时间`, visible: true},
        {key: 7, label: `可用油站`, visible: true},
        {key: 8, label: `可用油品`, visible: true},
        {key: 9, label: `可用星期`, visible: true},
        {key: 10, label: `是否可以转赠`, visible: false},
        {key: 11, label: `是否可以叠加`, visible: false},
        {key: 12, label: `延迟天数`, visible: false},
        {key: 13, label: `使用目的`, visible: false},
        {key: 14, label: `使用说明`, visible: false},
        {key: 15, label: `排序编码`, visible: false},
        {key: 16, label: `创建时间`, visible: false},
        {key: 17, label: `备注信息`, visible: false}
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        couponName: [
          {
            required: true, message: "优惠券名称不能为空", trigger: "blur"
          }
        ],
        couponType: [
          {
            required: true, message: "优惠券类型不能为空", trigger: "change"
          }
        ],
        consumptionAmount: [
          {
            required: true, message: "消费金额不能为空", trigger: "blur"
          }
        ],
        discountAmount: [
          {
            required: true, message: "优惠金额不能为空", trigger: "blur"
          }
        ],
        startTime: [
          {
            required: true, message: "开始时间不能为空", trigger: "blur"
          }
        ],
        endTime: [
          {
            required: true, message: "结束时间不能为空", trigger: "blur"
          }
        ],
        stationsLimit: [
          {
            required: true, message: "可用油站不能为空", trigger: "blur"
          }
        ],
        fuelsLimit: [
          {
            required: true, message: "可用油品不能为空", trigger: "blur"
          }
        ],
        daysLimit: [
          {
            required: true, message: "可用星期不能为空", trigger: "blur"
          }
        ],
        discountRatio: [
          {
            required: true, message: "折扣比例不能为空", trigger: "blur"
          }
        ]
      }
    };
  },
  computed: {
    // 是洗车劵
    isWash: function () {
      return this.form.couponType == 4;
    },
    // 是折扣券
    isDiscount: function () {
      return this.form.couponType == 2;
    }
  },
  created() {
    this.getList();
    selectStationList().then(res => {
      this.stationList = res.data;
    });
    selectFuelList().then(res => {
      this.fuelList = res.data;
    });
  },
  methods: {
    formatDateTime,
    /** 查询优惠券模板列表 */
    getList() {
      this.loading = true;
      listCouponTemplate(this.queryParams).then(response => {
        this.couponTemplateList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        mchId: undefined,
        couponName: undefined,
        couponType: undefined,
        consumptionAmount: undefined,
        discountAmount: undefined,
        discountRatio: undefined,
        startTime: undefined,
        endTime: undefined,
        stationsLimit: undefined,
        fuelsLimit: undefined,
        daysLimit: undefined,
        transferable: undefined,
        stackable: undefined,
        delayDays: undefined,
        purpose: undefined,
        instructions: undefined,
        orderNumber: undefined
      };
      this.resetForm("form");
      this.checkWeekList = [];
      this.checkFuelList = [];
      this.checkStationList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleSortChange(data) {
      console.log('handleSortChange')
      console.log(data)
      if (data.order) {
        if (data.order.indexOf('asc') > -1) {
          this.queryParams.sortOrder = 'asc'
        } else {
          this.queryParams.sortOrder = 'desc'
        }
        this.queryParams.sortName = data.prop
      }
      console.log(this.queryParams)
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
      this.checkWeekList = [];
      this.checkFuelList = [];
      this.checkStationList = [];
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加优惠券模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getCouponTemplate(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.dateRange = [formatDateTime(this.form.startTime), formatDateTime(this.form.endTime)];
        this.checkStationList = this.form.stationsLimit.split(',');
        this.checkFuelList = this.form.fuelsLimit.split(',');
        this.checkWeekList = this.form.daysLimit.split(',');
        this.open = true;
        this.title = "修改优惠券模板";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.daysLimit = this.checkWeekList.join(',')
      this.form.fuelsLimit = this.checkFuelList.join(',')
      this.form.stationsLimit = this.checkStationList.join(',')
      if (this.dateRange.length > 1) {
        this.form.startTime = this.dateRange[0]
        this.form.endTime = this.dateRange[1]
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateCouponTemplate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addCouponTemplate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除优惠券模板编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delCouponTemplate(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/couponTemplate/export', {
        ...this.queryParams
      }, `couponTemplate_${nowCnFormatDateTime()}.xlsx`)
    }
  }
}

</script>

<style>
.el-form .el-select {
  width: 100%;
}
</style>
